#include <sstream>
#include <cstdlib>
#include "TimeStamp.h"


/* CTor */
TimeStamp::TimeStamp(const std::string& str){
	Assign(str);
}

void TimeStamp::Assign(const std::string& str){
	if(strlen(str.c_str()) != 14)
		throw LENGTH;
	year  = atoi(str.substr(0, 4).c_str());
	month = atoi(str.substr(4, 2).c_str());
	if(month > 12 || month < 1)
		throw MONTH;
	day	  = atoi(str.substr(6, 2).c_str());
	if(day < 1)
		throw DAY;
	if((month == 1 || 3 || 5 || 7 || 8 || 10 || 12) && day > 31)
		throw DAY;
	if((month == 4 || 6 || 9 || 11) && day > 30)
		throw DAY;
	if((month == 2) && (day > 29 || (day > 28 && (year % 4 != 0 || (year % 100 == 0 && year % 400 != 0)))))
		throw DAY;
	hour  = atoi(str.substr(8, 2).c_str());
	if(hour > 59 || hour < 0)
		throw HOUR;
	min	  = atoi(str.substr(10, 2).c_str());
	if(min > 59 || min < 0)
		throw MIN;
	sec	  = atoi(str.substr(12, 2).c_str());
	if(sec > 59 || sec < 0)
		throw SEC;
}

TimeStamp TimeStamp::StepByHours(const int& hours){
	if (hour + hours > 24){
		hour += hours - 24;
		day += 1;	// TODO: StepByHours
	}

	return *this;
}

std::ostream& operator<<(std::ostream& os, const TimeStamp& ts){
	os << ts.year << "." << ts.month << "." << ts.day << " " << ts.hour << ":" << ts.min << ":" << ts.sec;
	return os;
}

std::istream& operator>>(std::istream& is, TimeStamp& ts){
	std::string temp;
	is >> temp;
	ts.Assign(temp);
	return is;
}

/* Global Functions */
bool operator<(const TimeStamp& ts1, const TimeStamp& ts2){
	if(ts1.OneStr() < ts2.OneStr())
		return true;
	return false;
}
